import { Injectable } from '@nestjs/common'
import { Prisma } from '@prisma/client'
import { PrismaService } from 'nestjs-prisma'
import { DomainModel } from '../model'

@Injectable()
export class FlowPlatformDao {
  get table() {
    return this.prismaService.flowPlatform
  }

  constructor(private readonly prismaService: PrismaService) {}

  /**
   * 根据platform取数据
   * @param platform
   * @returns
   */
  getByPlatform(platform: string) {
    return this.table.findUnique({
      where: {
        platform,
      },
    })
  }

  /**
   * platform是否已经存在
   * @param data
   * @returns
   */
  isPlatformExists(data: { platform: string; id?: number }) {
    return this.table
      .count({
        where: {
          platform: data.platform,
          id: {
            not: data.id,
          },
        },
      })
      .then(count => count > 0)
  }

  /**
   * label是否已存在
   * @param data
   * @returns
   */
  isLabelExists(data: { label: string; id?: number }) {
    return this.table
      .count({
        where: {
          label: data.label,
          id: {
            not: data.id,
          },
        },
      })
      .then(count => count > 0)
  }

  /**
   * 添加数据
   * @param data
   * @returns
   */
  save(data: Prisma.FlowPlatformCreateInput): Promise<DomainModel.FlowPlatform> {
    return this.table.create({ data })
  }

  /**
   * 根据ID更新数据
   * @param id
   * @param data
   * @returns
   */
  updateById(id: number, data: Prisma.FlowPlatformUpdateInput): Promise<DomainModel.FlowPlatform> {
    return this.table.update({ data, where: { id } })
  }

  /**
   * 根据ID删除数据
   * @param id
   * @returns
   */
  deleteById(id: number): Promise<DomainModel.FlowPlatform> {
    return this.table.delete({ where: { id } })
  }

  /**
   * 根据ID获取数据
   * @param id
   * @returns
   */
  getById(id: number): Promise<DomainModel.FlowPlatform> {
    return this.table.findUnique({
      where: {
        id,
      },
    })
  }

  /**
   * 数据列表
   * @param data
   * @returns
   */
  list(data: Prisma.FlowPlatformWhereInput): Promise<DomainModel.FlowPlatform[]> {
    return this.table.findMany({
      where: data,
      orderBy: {
        createTime: 'desc',
      },
    })
  }
}
